package com.example.camunda.rest;

import com.example.camunda.dto.ProcessInstanceDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 流程实例
 *
 * @author heshao
 * @date 2021/11/9 13:48
 **/
@Api(tags = "流程实例")
@RestController
@RequestMapping("/process-instance")
public class ProcessInstanceController {

    private final RuntimeService runtimeService;


    public ProcessInstanceController(RuntimeService runtimeService) {
        this.runtimeService = runtimeService;
    }

    @GetMapping
    @ApiOperation("查询所有流程实例")
    public Page<ProcessInstanceDto> list(@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        long count = query.count();
        List<ProcessInstance> list = query.listPage(pageNum * pageSize, pageSize);
        List<ProcessInstanceDto> dtoList = list.stream().map(ProcessInstanceDto::from).collect(Collectors.toList());
        return new PageImpl<>(dtoList, PageRequest.of(pageNum, pageSize), count);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询流程实例")
    public ProcessInstanceDto get(@PathVariable String id) {
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(id).singleResult();
        return ProcessInstanceDto.from(instance);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除流程实例")
    public void delete(@PathVariable String id, String reason) {
        runtimeService.deleteProcessInstance(id, reason);
    }

    @PutMapping("/{id}/suspended")
    @ApiOperation("激活/挂起流程实例")
    public void suspended(@PathVariable String id) {
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(id).singleResult();
        if (instance.isSuspended()) {
            runtimeService.activateProcessInstanceById(id);
        } else {
            runtimeService.suspendProcessInstanceById(id);
        }
    }
}
